from flask import request
from flask_restplus import Resource

from api.response import Response
from api.restplus import api
from api.v1 import serializers
from system import variables
from system.files_operation import mkdir, cleandir, create_file, justify_file_exist
from system.image_detector import object_detect

ns = api.namespace(variables.V1_NAMESPACE,
                   description=f"API Version {variables.V1_VERSION}")


def request_parse(req_data):
    # '''解析请求数据并以json形式返回'''
    data = {}
    if req_data.method == 'POST':
        data = req_data.json
    elif req_data.method == 'GET':
        data = req_data.args
    return data


# @ns.route("/")
# class Index(Resource):
#     def get(self):
#         return Response.success({
#             "description": f"{variables.SERVICE_LABEL} API "
#                            f"{variables.V1_NAMESPACE}",
#             "status": "online",
#             "version": variables.V1_VERSION
#         })


# @ns.route("/auth/register/")
# class Index(Resource):
#     @api.expect(serializers.register, validate=True)
#     def post(self):
#         body = request.json
#
#         Logger.info("A user as been registered (%s, %s).",
#                     body["username"], body["email"])
#
#         return Response.success(body, status=201)


@ns.route("/preloading")
class Preloading(Resource):
    @api.expect(serializers.preloading)
    @api.response(code=200, model=serializers.preloading_res, description="工程描述文件下载")
    def post(self):
        # {"project": project, "properties": properties}
        data = request_parse(request)
        project = data["project"]
        properties = data["properties"]
        # 创建文件夹状态 boolean
        ds = mkdir(project["id"])

        if not ds:
            # 创建失败 已存在 清空文件夹重新下载
            cleandir(project["id"])
        create_file(project["id"], "req.json", data)

        # TODO: 执行仿真 ，异步， 多线程
        create_file(project["id"], "res.json", {})

        return Response.success({
            "success": True,
            "message": "success",
        })


@ns.route("/simulate")
class Detector(Resource):
    @api.expect(serializers.preloading)
    @api.response(code=200, model=serializers.preloading_res, description="仿真结果输出")
    def post(self):
        data = request_parse(request)
        project_id = data["project_id"]

        if justify_file_exist(project_id, "res.json"):
            return Response.success({
                "success": True,
                "data": {},
            })
        else:
            return Response.success({
                "success": False,
                "message": "仿真过程未结束！",
            })